<?php

App::uses('AppModel', 'Model');

class LeaveType extends AppModel {
	
	public $hasMany = array('Leave', 'LeaveTypeRule');
	
	public $validate = array(
		'name' => array( 
			array(
				'rule'    => 'notEmpty',
				'message' => 'Name is required.'
			),
			array(
				'rule'    => 'isUnique',
				'message' => 'Type with the same name already exists.'
			),
		)
	);
	
	public function afterFind($collection=array(), $primary=false) {
	    foreach ($collection as &$row) {
	        if (! empty($row['LeaveTypeRule'])) {
	            foreach ($row['LeaveTypeRule'] as $rule) {
	                $row['LeaveTypeRuleIndexed'][$rule['rule']] = $rule;
	            }
	        }
	    }
	    
	    return $collection;
	}
	
	/**
	 * remove related entities before saving
	 * @param array $options
	 */
	public function beforeSave($options=array()) {
		if ($this->id) {
			$this->LeaveTypeRule->deleteAll(array(
				'leave_type_id' => $this->id
			));
		}
	}
	
	/**
	 * refactor LeaveType data
	 * @param array $data
	 */
	public function refactor($data) {
	    $leaveTypeRules = array();
	    foreach ($data['LeaveTypeRule'] as $ltr) {
	        if (! empty($ltr['rule'])) {
	            if (empty($ltr['arguments'])) {
	                $ltr['arguments'] = array();
	            }
                $ltr['arguments'] = json_encode($ltr['arguments']);
	            $leaveTypeRules[] = $ltr;
	        }
	    }
	    $data['LeaveTypeRule'] = $leaveTypeRules;
	    
	    return $data;
	}
	
}

?>